<template>
    <!-- <h3 class="test-paper">考试页</h3> -->
    <div class="test-paper">
         <div class="test-top">
            <h4 class="title">名称: <span>{{ name }}</span></h4>
            <p class="message">距离考试结束 {{ formatime(second) }}</p>
            <div class="num">【<span>{{ total }}</span>/ <span> {{ current }}</span>】</div>
         </div>
         <div class="test-content">
               <div class="item" v-if="data">
                    <div class="q">{{ current + 1}}.{{ data.question }}</div>
                    <ul>
                         <li 
                            v-for="(item,n) in data.opt"
                            :class="item.isSelect == true ? 'active':''" @click="selectAnswerFn(item.key,n)">
                            {{ item.key }}.{{ item.value }}
                        </li>
                    </ul>
               </div>
         </div>
         <div class="test-footer">
             <div class="left">
                <van-button @click="prevFn" plain hairline type="primary" size="small">上一题</van-button>
                <van-button @click="nextFn" plain hairline type="success" size="small">下一题</van-button>
             </div>
             <div class="right">
                <van-button type="danger" @click="submitExamFn" size="small">提交试卷</van-button>
             </div>
         </div>
         <div class="test-show-box">
             <ol>
                <li  v-for="(item,i) in tableData" :class="item.isSelect == true ?'active':''" @click="showCurrent(i)">{{ i+1 }}</li>
             </ol>
         </div>
    </div>
</template>

<script setup lang="ts">
import { useRouter , useRoute} from 'vue-router'
import request from '@/api/request';
import { ref } from 'vue';
import { showFailToast, showToast } from 'vant';
const $router = useRouter()
const $route = useRoute()

let { eid ,name, time } = $route.query as any;
let second = ref<any>(0)
let tableData = ref<any>([])
let dingshiqi = null as any
let current = ref<number>(0)
let data = ref<any>({});
let total = ref(0)

// 获取token
// 用户的临时身份
let token = localStorage.getItem("AUTOTOKEN")

// 记录用户所选的答案
let answers = [] as any;


if(time) {
    second.value = time * 60 * 60 ; 
    dingshiqi = setInterval(()=>{
        second.value --;
        if(second.value == 0) {
            clearInterval(dingshiqi)
        }
    },1000)
}

// 格式化时间
const formatime = (value:number) => {
    let h:number | string = 0, m:number | string = 0 , s:number | string = 0;
    h = Math.floor(value / 3600);
    m = Math.floor(value % 3600 / 60);
    s = Math.floor(value % 60);
    h = h < 10 ? '0'+h:h ;
    m = m < 10 ? '0'+m:m ;
    s = s < 10 ? '0'+s:s ;
    return `${h}:${m}:${s}`
}

// 获取试卷题目列表
const getTestPaper = async () => {
    if(eid){
        await request.topicList({eid})
        .then(
            (content: any )=> {
                console.log(content)
                let {code ,msg ,result} = content;
                if(code == 200) {
                    let arr = result.map((item: any)=>{
                        // console.log(item.opt)
                        item.opt = JSON.parse(item.opt);
                        // console.log(item.opt)
                        return item;
                    })
                    tableData.value = arr;
                    total.value = arr.length;
                    data.value = arr[current.value];
                }
                else {
                    showFailToast(msg)
                }
            }
        )
    }
    
}

// 选择题目
const selectAnswerFn = (key: string, n:number)=> {
    if(!token) return false;
    data.value.opt.forEach((element: any) => {
        element.isSelect = undefined;
    });
    data.value.opt[n].isSelect = true;
    tableData.value[current.value].opt[n].isSelect = true;
    tableData.value[current.value].isSelect = true;
    // 记录用户所选择的答案
    answers[current.value] = key;
}

const showCurrent = (i:number) => {
    current.value = i;
}


// 下一题
const nextFn = ()=> {
    if(!token) return false;
    current.value ++;
    if(current.value > tableData.value.length - 1) {
        current.value =  tableData.value.length - 1;
        return false;
    }
    data.value = tableData.value[current.value];
}
// 上一题
const prevFn = ()=> {
    if(!token) return false;
    current.value --;
    if(current.value < 0) {
        current.value = 0;
        return false;
    }
    data.value = tableData.value[current.value];
}


// 定义分数 答题选项等等
let score = 0;
let wrong = 0;
let right = 0;
// nickName,account,name,score,wrong,right,myanswer,time
let nickName = localStorage.getItem("NICKNAME")
let account = localStorage.getItem("ACCOUNT")

// 提交试卷
const submitExamFn = async () => {
    if(!token) return false;
    let arr = tableData.value;
    for(let i = 0 ; i < arr.length ; i ++){
        if(arr[i].answer == answers[i]) {
            // 统计分数
            score += arr[i].score;
            right ++;
        }
        else {
            wrong ++;
        }
    }
    let myanswer = JSON.stringify(answers)
    console.log("我的答案:",myanswer)
    // 添加成绩
    await request.examScoreAdd({token, nickName,account,name,score,wrong,right,myanswer,time: (time * 60 * 60) - second.value})
    .then(
        (content: any)=>{
            let {code,msg} = content;
            console.log(content)
            if(code == 200) {
                showToast(msg)
                setTimeout(()=>{
                    $router.replace({path:'/score'})
                },300)
            }
            else {
                showFailToast(msg);
            }
        }
    )
}

getTestPaper();



// JS 禁止刷新页面
// window.addEventListener('beforeunload', function (event) {
//     const confirmationMessage = "确定要离开此页面吗？您所做的更改可能不会被保存。";
//     event.preventDefault();
//     event.returnValue = confirmationMessage; 
//     return confirmationMessage;
// });

</script>
 
<style lang="less">
 @import '../../static/less/variable.less';
.test-paper {
    padding: @pad;
    .test-top {
        .title {
            height: 40px;
            line-height: 40px;
            font-size: 18px;
        }
        .message {
            font-size: 16px;
            padding: 5px 0;
        }
        .num {
            font-size: 18px;
            text-align: center;
        }
    }
    .test-content {
        .item {
            .q {
                font-size: 18px;
                margin-bottom: 10px;
                font-weight: bold;
            }
            ul {
                li {
                    font-size: 16px;
                    padding: 10px 10px;
                    margin-bottom: 15px;
                    &.active {
                        background-color: yellowgreen;
                        border-radius: 5px;
                        color: #fff;
                    }
                }
            }
        }
    }
    .test-footer {
        width: 100%;
        display: flex;
        justify-content: space-between;
        position: fixed;
        bottom: 70px;
        left: 0;
        padding: @pad;
        z-index: 1000;
        .left {
            button {
                margin-right: 10px;
            }
        }
    }
}
.test-show-box {
    padding: 10px;
    width: 100%;
    position: fixed;
    bottom: 10px;
    left: 0;
    min-height: 200px;
    ol {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        li {
            font-size: 12px;
            width: 20px;
            height: 20px;
            border: 1px solid #ccc;
            border-radius: 2px;
            text-align: center;
            line-height: 20px;
            margin: 5px 1px;
            &.active {
                background-color: @bgColor;
                color: #fff;
            }
        }
    }
}
</style>